import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.contrib.layers.python.layers import layers

mnist = input_data.read_data_sets('mnist_data/', one_hot=True)

# 定义参数
images_ = tf.placeholder(tf.float32, [None, 784], name='images')
images = tf.reshape(images_, shape=[-1, 28, 28, 1])
labels = tf.placeholder(tf.float32, [None, 10], name='labels')

# 构建卷积网络
# layer_1
convolution_1 = layers.conv2d(images, 32, 5, 1)  # 28x28x32
pooling_1 = layers.max_pool2d(convolution_1, 2, 2)  # 14x14x32

# layer_2
convolution_2 = layers.conv2d(pooling_1, 64, 5, 1)   # 14x14x64
pooling_2 = layers.max_pool2d(convolution_2, 2, 2)  # 7x7x64

# layer_3  全局平均池化层
full_pooling = layers.avg_pool2d(pooling_2, [7, 7], stride=7, padding='SAME')
full_pooling = tf.reshape(full_pooling, shape=[-1, 64])

y_pre = layers.fully_connected(full_pooling, 10, activation_fn=tf.nn.softmax)

cross_entropy = -tf.reduce_sum(labels * tf.log(y_pre))
train_op = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

correct_prediction = tf.equal(tf.argmax(y_pre, 1), tf.argmax(labels, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))

training_epochs = 1000
batch_size = 100

# 启动训练
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    for epoch in range(training_epochs):
        total_batch = mnist.train.num_examples // batch_size
        for i in range(total_batch):
            images_train, labels_train = mnist.train.next_batch(batch_size)
            sess.run(train_op, feed_dict={images_: images_train, labels: labels_train})
            print('Accuracy: ', accuracy.eval({images_: images_train, labels: labels_train}))